package com.hzx.ssm.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.hzx.ssm.util.JedisPoolUtil;
import com.hzx.ssm.util.RedisAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;


@RestController
public class KaptchaController {

    @Autowired
    private Producer captchaProducer;
    @Autowired
    private JedisPool jedisPool;
    private Jedis jedis;
    @GetMapping("/kaptcha")
    public void kaptcha(HttpServletResponse response, HttpServletRequest request,
                        @RequestParam("user_id")String user_id) throws IOException {
        response.setDateHeader("Expires", 0);    // 禁止服务器端缓存
        // 设置标准的 HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // 设置IE扩展 HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");    // 设置标准 HTTP/1.0 不缓存图片
        response.setContentType("image/jpeg");    // 返回一个 jpeg 图片，默认是text/html(输出文档的MIMI类型)

        String capText = captchaProducer.createText();    // 为图片创建文本

        RedisAPI.set(user_id,capText);
        System.out.println(RedisAPI.get(user_id));;
        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);


        BufferedImage img = captchaProducer.createImage(capText); // 创建带有文本的图片
        ServletOutputStream out = response.getOutputStream();
        // 图片数据输出
        ImageIO.write(img, "jpeg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }
}
